<?php
declare(strict_types=1);

namespace app\validate\api\admin\general;

use app\validate\api\ApiBaseValidate;
use app\model\api\admin\general\Dict;
use zhtp\ConstUtil;

class DictValidate extends ApiBaseValidate
{
    protected $_v_model = Dict::class;

    protected $ex_data = [];

    protected $rule = [];

    protected $message = [];

    public function __construct()
    {
        parent::__construct();

        $this->rule = [
            'id' => 'require|integer',
            'pid' => 'require|integer',
            'title|字典名' => 'max:64',
            'type|类型' => 'require|in:' . ConstUtil::getAllValues(Dict::TYPE),
            'value|字典值' => 'max:255|isKvUnique',
            'extend|扩展' => 'max:512',
            'sort|排序' => 'integer',
            'status|状态' => 'require|in:0,1',
            'remark|备注' => 'max:255',

            // 扩展
            'del_ids' => 'require|hasChild',
        ];
    }

    protected $scene = [
        'save' => ['pid', 'title', 'type', 'value', 'extend', 'sort', 'status', 'remark'],
        'update' => ['id', 'pid', 'title', 'type', 'value', 'extend', 'sort', 'status', 'remark'],
        'delete' => ['del_ids'],
    ];

    protected function isKvUnique($value, $rule, $data = [])
    {
        $m = Dict::field('id');
        if (isset($data['id']) && $data['id'] > 0) {
            $m->where('id', '<>', $data['id']);
        }

        if ($data['type'] == Dict::TYPE['KEY'][0]) {
            $m->where([
                ['type', '=', Dict::TYPE['KEY'][0]],
                ['value', '=', $value]
            ]);

            $re = $m->find();
            if ($re) {
                return "字典键重复:{$value}";
            }
        } elseif ($data['type'] == Dict::TYPE['VALUE'][0]) {
            $m->where([
                ['type', '=', Dict::TYPE['VALUE'][0]],
                ['value', '=', $value],
                ['pid', '=', $data['pid']] // 相同父级下不能重复
            ]);

            $re = $m->find();
            if ($re) {
                return "字典值重复:{$value}";
            }
        }
        return true;
    }

    protected function hasChild($value, $rule, $data = [])
    {
        $m = Dict::where([
            ['pid', 'in', $data['del_ids']]
        ])
            ->field('id')
            ->select();

        if (!$m->isEmpty()) {
            return '存在子级，无法删除';
        }
        return true;
    }
}
